package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.util.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if ("list".equals(operation)) {
            list(request, response);
        } else if ("toAdd".equals(operation)) {
            toAdd(request, response);
        } else if ("save".equals(operation)) {
            save(request, response);
        } else if ("toEdit".equals(operation)) {
            toEdit(request, response);
        } else if ("edit".equals(operation)) {
            edit(request, response);
        } else if ("delete".equals(operation)) {
            delete(request, response);
        }else if("toTestUpload".equals(operation)){
            toTestUpload(request,response);
        }else if("testUpload".equals(operation)){
            testUpload(request,response);
        }else if("downloadReport".equals(operation)){
            downloadReport(request,response);
        }
    }

    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //返回的数据类型为文件xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("测试文件名.xlsx".getBytes(),"iso8859-1");
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);

        //生成报告的文件，然后传递到前端页面
        ByteArrayOutputStream os = questionService.getReport();
        //获取产生响应的流对象
        ServletOutputStream sos = response.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //将输出流刷新
        sos.flush();
        os.close();
    }

    private void toTestUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request,response);
    }

    private void testUpload(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
            if(ServletFileUpload.isMultipartContent(request)){
                //2.创建磁盘工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //3.Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //4.从request中读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    //5.当前表单是否是文件表单
                    if(!fileItem.isFormField()){
                        //6.从临时存储文件的地方将内容写入到指定位置
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),fileItem.getName()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int size = 5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = questionService.findAll(page, size);
        request.setAttribute("page",all);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request,response);
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Company> companyList = companyService.findAll();
        request.setAttribute("companyList",companyList);
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("catalogList",catalogList);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request,response);
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
            if(ServletFileUpload.isMultipartContent(request)){
                //2.创建磁盘工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //3.Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //4.从request中读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(request);

                //创建一个标记位,标记当前时候有上传文件的操作
                boolean flag = false;
                for (FileItem item : fileItems) {
                    if(StringUtils.isNotBlank(item.getName())){
                        flag = true;
                        break;
                    }
                }

                // --处理form表单提交过来的普通数据
                //将数据获取到，封装成一个对象
                Question question = BeanUtil.fillBean(fileItems, Question.class);
                //调用业务层接口save获取picture的id
                String picture = questionService.save(question,flag);
                //处理form表单提交过来的文件数据
                for (FileItem item : fileItems) {
                    //5.当前表单是否是文件表单
                    if(!item.isFormField()){
                        //6.从临时存储文件的地方将内容写入到指定位置
                        item.write(new File(request.getServletContext().getRealPath("upload"),picture));
                    }
                }
            }
            response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Question question = questionService.findById(id);
        List<Company> companyList = companyService.findAll();
        request.setAttribute("companyList",companyList);
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("catalogList",catalogList);
        request.setAttribute("question",question);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request,response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
            if(ServletFileUpload.isMultipartContent(request)){
                //2.创建磁盘工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //3.Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //4.从request中读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                //创建一个标记位,标记当前时候有上传文件的操作
                boolean flag = false;
                for (FileItem item : fileItems) {
                    if(StringUtils.isNotBlank(item.getName())){
                        flag = true;
                        break;
                    }
                }

                // --处理form表单提交过来的普通数据
                //将数据获取到，封装成一个对象
                Question question = BeanUtil.fillBean(fileItems,Question.class);
                //调用业务层接口save
                questionService.update(question,flag);

                // --处理form表单提交过来的文件数据
                for(FileItem item : fileItems){
                    //5.当前表单是否是文件表单
                    if(!item.isFormField()){
                        //6.从临时存储文件的地方将内容写入到指定位置
                        item.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                    }
                }
            }
            //跳转回到页面list
            response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Question question = BeanUtil.fillBean(request, Question.class);
        questionService.delete(question);
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }
}
